package com.besttone.search.dialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import com.besttone.search.Client;
import com.besttone.search.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ProgressBarDialog extends Dialog
{

	private ProgressBar mProgress;
	private TextView mProgressNumber;
	private TextView mProgressPercent;
	public static final int M = 1024 * 1024;
	public static final int K = 1024;
	private double dMax;
	private double dProgress;
	private int middle = K;
	private int prev = 0;
	private Handler mViewUpdateHandler;
	private int fileSize;
	private int downLoadFileSize;
	private static final NumberFormat nf = NumberFormat.getPercentInstance();
	private static final DecimalFormat df = new DecimalFormat("###.##");
	private static final int msg_init = 0;
	private static final int msg_update = 1;
	private static final int msg_complete = 2;
	private static final int msg_error = -1;
	private String mUrl;
	private File fileOut;
	private String downloadPath;

	public ProgressBarDialog(Context context)
	{
		super(context);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		LayoutInflater inflater = LayoutInflater.from(getContext());
		mViewUpdateHandler = new Handler()
		{

			@Override
			public void handleMessage(Message msg)
			{
				super.handleMessage(msg);

				if (!Thread.currentThread().isInterrupted())
				{
//					Log.i("msg what", String.valueOf(msg.what));
					switch (msg.what)
					{
						case msg_init:
							// pbr.setMax(fileSize);

							mProgress.setMax(100);

							break;
						case msg_update:
							setDProgress((double) downLoadFileSize);
							break;
						case msg_complete:
							setTitle("文件下载完成");

							break;
						case msg_error:
							String error = msg.getData().getString("更新失败");
							setTitle(error);

							break;

						default:
							break;
					}
				}

				double precent = dProgress / dMax;

				if (prev != (int) (precent * 100))
				{
					mProgress.setProgress((int) (precent * 100));
					mProgressNumber.setText(df.format(dProgress) + "/" + df.format(dMax) + (middle == K ? "K" : "M"));
					mProgressPercent.setText(nf.format(precent));
					prev = (int) (precent * 100);
				}

			}
		};
		View view = inflater.inflate(R.layout.dialog_progress_bar, null);
		mProgress = (ProgressBar) view.findViewById(R.id.progress);
		mProgress.setMax(100);
		mProgressNumber = (TextView) view.findViewById(R.id.progress_number);
		mProgressPercent = (TextView) view.findViewById(R.id.progress_percent);
		setContentView(view);
		onProgressChanged();
		super.onCreate(savedInstanceState);

	}

	private void onProgressChanged()
	{
		mViewUpdateHandler.sendEmptyMessage(0);
	}

	public double getDMax()
	{
		return dMax;
	}

	public void setDMax(double max)
	{
		if (max > M)
		{
			middle = M;
		}
		else
		{
			middle = K;
		}
		dMax = max / middle;
	}

	public double getDProgress()
	{
		return dProgress;
	}

	public void setDProgress(double progress)
	{
		dProgress = progress / middle;
		onProgressChanged();
	}

	// String downloadPath = Environment.getExternalStorageDirectory().getPath()
	// + "/download_cache";

	public void downLoadFile(final String httpUrl)
	{
		this.mUrl = httpUrl;
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		// 判断sd卡是否存在
		if (sdCardExist)
		{
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
			if (getAvailableExternalMemorySize() < 50000000)
			{
				Toast.makeText(Client.getContext(), "存储空间不足", Toast.LENGTH_SHORT).show();
				dismiss();
				return;
			}
		}
		else
		{
			Toast.makeText(Client.getContext(), "SD卡不存在", Toast.LENGTH_SHORT).show();
			dismiss();
			return;
		}
		downloadPath = sdDir + "/114update";

		Client.getThreadPoolForDownload().execute(new Runnable()
		{
			@Override
			public void run()
			{
				// TODO Auto-generated method stub
				URL url = null;
				try
				{
					url = new URL(mUrl);

					String fileName = mUrl.substring(mUrl.lastIndexOf("/"));
					// String downloadPath = sdDir+"/114update";
					File tmpFile = new File(downloadPath);
					if (!tmpFile.exists())
					{
						tmpFile.mkdir();
					}
					fileOut = new File(downloadPath + fileName);
					// URL url = new URL(appurl);
					// URL url = new URL(mUrl);

					HttpURLConnection con;
					con = (HttpURLConnection) url.openConnection();
					InputStream in;
					in = con.getInputStream();

					fileSize = con.getContentLength();
					setDMax((double) fileSize);

					FileOutputStream out = new FileOutputStream(fileOut);
					byte[] bytes = new byte[1024];

					downLoadFileSize = 0;
					setDProgress((double) downLoadFileSize);
					sendMsg(msg_init);
					int c;
					while ((c = in.read(bytes)) != -1)
					{
						out.write(bytes, 0, c);
						downLoadFileSize += c;
						sendMsg(msg_update);// 更新进度条
					}
					in.close();
					out.close();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					sendMsg(msg_error);// error
				}
				sendMsg(msg_complete);// 下载完成
				Client.postRunnable(new Runnable()
				{

					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						dismiss();
						installApk(fileOut);
						exitApp();
					}
				});

			}
		});
	}

	private void sendMsg(int flag)
	{
		Message msg = new Message();
		msg.what = flag;

		mViewUpdateHandler.sendMessage(msg);

	}

	private void installApk(File file)
	{
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		String type = "application/vnd.android.package-archive";
		intent.setDataAndType(Uri.fromFile(file), type);
		Client.getContext().startActivity(intent);
		Log.e("success", "the end");
	}

	// 彻底关闭程序
	protected void exitApp()
	{
		Client.release();
		System.exit(0);
		// 或者下面这种方式
		// android.os.Process.killProcess(android.os.Process.myPid());
	}

	public static long getAvailableExternalMemorySize()
	{

		if (externalMemoryAvailable())
		{

			File path = Environment.getExternalStorageDirectory();

			StatFs stat = new StatFs(path.getPath());

			long blockSize = stat.getBlockSize();

			long availableBlocks = stat.getAvailableBlocks();

			return availableBlocks * blockSize;

		}
		else
		{

			return msg_error;

		}
	}

	public static boolean externalMemoryAvailable()
	{

		return android.os.Environment.getExternalStorageState()

		.equals(android.os.Environment.MEDIA_MOUNTED);

	}
}